""" Various functions used in loading and parsing data from resource files. """

import os
import xml.etree.ElementTree as ET
from .. import debug, resource
from ..error import FormatError
from ..misc import strbool

def get_elem_value(elem,valType,default=0):
    """ Returns a value of the specified type from a text element.
        Pass an XML element or None. The function will attempt to convert the
        text value to an integer. If an error occurs, `default` is returned.
    """
    try:
        return valType(elem.text)
    except (TypeError,AttributeError,ValueError):
        return default

#def parse_xml(fileOrPath,typeID,version=None):
#    """ Helper function for parsing XML data.
#        
#        For `fileOrPath`, pass a path to a resource XML file or a file-like
#        object containing resource XML data.
#        
#        For `version`, pass the expected version. If the file does not appear
#        to be that version a FormatError is raised. 
#        
#        For `typeID`, pass the value expected for the resource type ID.
#        A FormatError will be raised if the value in the XML does not match what
#        was passed.
#        
#        Parses a resource XML file and returns the parsed data in the form
#        of a dictionary:
#        ['id'] : The ID of the resource.
#        ['version'] : The version of the resource data.
#        ['type'] : The type ID of the resource.
#        ['depend'] : List of IDs of dependency resources.
#        ['data'] : An etree Element object containing the `data` section of the
#                   resource XML.
#        
#        Parsing is very strict. If an error is found in the data format, a
#        FormatError will be raised that explains the error.
#        
#        FIXME: This function should be moved to resfile/__init__.py
#        FIXME: Does not tolerate excess whitespace in values.
#        FIXME: Does not treat tag and attribute names as case-insensitive.
#    """
#    data = {}
#    # Open the tree and find the root.
#    tree = ET.parse(fileOrPath)
#    root = tree.getroot()
#    # Fail if the root is not 'resource'.
#    if root.tag != 'resource':
#        raise FormatError(
#            'Resource file "%s" contains no root element "resource".'%fileOrPath)
#    # Verify and store all required root attributes
#    data['id'] = root.get('id')
#    if data['id'] is None:
#        raise FormatError('Resource file "%s" has no ID.'%fileOrPath)
#    data['type'] = root.get('type')
#    if data['type'] is None:
#        raise FormatError('Resource file "%s" has no type ID.'%fileOrPath)
#    if data['type'] != typeID:
#        raise FormatError('Resource file "%s" has unexpected ID.'%fileOrPath)
#    data['version'] = root.get('version')
#    if data['version'] is None:
#        raise FormatError('Resource file "%s" has no version number.'%fileOrPath)
#    # Fail if the version is unsupported.
#    if version is not None and data['version'] != version:
#        raise FormatError(
#          'Resource file "%s" has an unsupported version number "%s".'
#          %(fileOrPath,data['version']))
#    # Loop through root elements
#    data['depend'] = []
#    foundDepends = False
#    foundData = False
#    for e in root:
#        # Parse the dependency section.
#        if e.tag == 'depends':
#            # Make sure only one dependency section exists.
#            if not foundDepends:
#                foundDepends = True
#            else:
#                raise FormatError(
#                  'Resource file "%s" contains more than one dependency section'
#                  %FileOrPath)
#            # Load the dependency resources.
#            for e2 in e:
#                # Validate tags in dependency section
#                if e2.tag != 'depend':
#                    raise FormatError(
#                      'Resource file "%s" dependency section contains invalid element "%s"'
#                      %(fileOrPath,e2.tag))
#                # Validate and store dependency info
#                ref = e2.get('ref')
#                if ref is None:
#                    raise FormatError(
#                      'Resource file "%s" contains dependency with no reference.'
#                      %fileOrPath)
#                data['depend'].append(ref)
#        # Store the data section, but don't parse it.
#        elif e.tag == 'data':
#            # Fail on duplicate data sections
#            if not foundData:
#                foundData = True
#            else:
#                raise FormatError(
#                  'Resource file "%s" contains multiple `data` sections.'
#                  %fileOrPath)
#            data['data'] = e
#        # Fail on unknown tags
#        else:
#            raise FormatError(
#              'Resource file "%s" root contains invalid element "%s".'
#              %(fileOrPath,e.tag))
#    # Fail if no data section was found.
#    if not foundData:
#        raise FormatError('Resource file "%s" contains no `data` section.'%fileOrPath)
#    
#    # We made it out of the woods.
#    return data